# -*- coding: utf-8 -*-
import json

import requests
from django.conf import settings

from common.bankcard import db as bankcard_db
from common.bankcard.model import BANK_CARD_TYPE
from common.bankcard.model import STAR_STRATEGY
from common.mch import db as mch_db
from common.third import hydra
from common.third.tonglue import tonglue_create_order
from common.utils import exceptions as err
from common.utils import track_logging
from common.utils.sign import generate_sign
from common.utils.telegram import send_text_msg_tele

_LOGGER = track_logging.getLogger(__name__)

CHARGE_HANDLE = {
    BANK_CARD_TYPE.RECHARGE: tonglue_create_order,
    BANK_CARD_TYPE.ORECHARGE: hydra.create_order,
    BANK_CARD_TYPE.AGENT_RECHARGE: tonglue_create_order,
}


def get_extra_info(user_id, star, ip):
    if star > 0:
        account_day, recharge, bet, recharge_count, withdraw_count, ratio = STAR_STRATEGY[star]
    else:
        account_day, recharge, bet, recharge_count, withdraw_count, ratio = [0, 0, 0, 0, 0, 0]
    return {
        "user_info": {
            "count_withdraw": withdraw_count,
            "tel": "13800010001",
            "account_day": account_day,
            "count_recharge": recharge_count,
            "device_ip": ip,
            "chn": "console_test",
            "user_id": 'test%s' % user_id,
            "total_bet": bet,
            "total_recharge": recharge,
            "ratio": ratio
        }
    }


def create_test_order(order_info, req_ip):
    mch_account = mch_db.get_account(order_info['mch_id'])
    if not mch_account:
        raise err.ParamError('mch_id invalid')
    extra_info = get_extra_info(order_info['user_id'], order_info['star'], req_ip)
    parameter_dict = {
        'sdk_version': 'ios_5.1',
        'mch_id': order_info['mch_id'],
        'user_id': '999999%s' % order_info['user_id'],
        'out_trade_no': '9999%s' % order_info['out_trade_no'],
        'body': u'控制台订单测试',
        'pay_type': order_info['pay_type'],
        'pay_account_num': order_info['pay_account_num'],
        'pay_account_username': order_info['pay_account_username'],
        'pay_account_bank': u'工商银行',
        'total_fee': order_info['total_fee'],
        'mch_create_ip': '127.0.0.1',
        'notify_url': 'http://219.135.56.195:8084/notify',
        'context': json.dumps(extra_info, ensure_ascii=False),
        'region': ''
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, mch_account.api_key)
    res = requests.post(settings.RECHARGE_URL, data=parameter_dict, timeout=3)
    return res.json()


def resend_recharge(order):
    user_star, bankcard = bankcard_db.get_bankcard_by_context(order.mch_id, order.context,
                                                              order.pay_type, order.pay_account_num,
                                                              order.sdk_version)
    CHARGE_HANDLE[bankcard.card_type](order, bankcard)


def send_reminder(order):
    msg_counter = 0
    header = u'收款卡异常告警    \r\n'
    footer = u'超过30分钟没有成功订单'
    msg = ''

    if order:
        if order["company"]:
            msg += u' 平台: ' + unicode(order["company"]) + u'\r\n'
            msg_counter += 1

        if order["card_code"]:
            msg += u' 卡号: ' + unicode(order["card_code"]) + u'\r\n'
            msg_counter += 1

        if order["card_type"]:
            msg += u' 卡种: ' + unicode(order["card_type"]) + u'\r\n'
            msg_counter += 1

        if order["level"] >= 0:
            msg += u' 星级: ' + unicode(order["level"]) + u'\r\n'
            msg_counter += 1

    if msg_counter > 1:
        message = "**" + header + "**" + '```' + msg + '``` ' + '__' + footer + '__'
        send_text_msg_tele(message)
        return True
    else:
        return False
